package com.hethongviet.vending.pages;

import java.io.InputStream;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Dialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.hethongviet.vending.AppMain;
import com.hethongviet.vending.Constant;
import com.hethongviet.vending.AppConfig;
import com.google.android.DemoKit.R;
import com.hethongviet.vending.Utils;
import com.hethongviet.vending.helper.CodeResult;
import com.hethongviet.vending.helper.TimerOutUtils;
import com.hethongviet.vending.helper.dialog.DialogMessageBack;
import com.hethongviet.vending.helper.dialog.DialogMessageConfirm;
import com.hethongviet.vending.model.Box;
import com.hethongviet.vending.model.Product;
import com.hethongviet.vending.model.ProductSell;
import com.hethongviet.vending.model.Transaction;

public class DetailProductActivity extends GeneralActivity
{

	private Button _buttonSellProduct = null;

	private Timer _timerOutProductDelevery = null;
	private TimerOutUtils _timerOutUtils = null;

	private ProductSell _productSell = null;

	public DetailProductActivity()
	{
		_productSell = null;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		/* Full screen */
		Utils.prepareWindow(this);

		setContentView(R.layout.page_detail_product);

		findViewById(R.id.button_back).setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View arg0)
			{
				setResult(RESULT_CANCELED);
				finish();
			}
		});

		final Product currentProduct = AppMain.getInstance().getCurrentBoxItem().getProduct();

		((TextView) findViewById(R.id.text_detail_product_title)).setText(currentProduct.getName());
		((TextView) findViewById(R.id.text_detail_product_description)).setText(currentProduct.getDescription());
		((TextView) findViewById(R.id.text_detail_product_price)).setText(currentProduct.getPrice()
				+ "");

		/* Image of the product */
		InputStream inputStream = null;
		try
		{
			inputStream = getAssets().open(
					"products/" + currentProduct.getCode() + ".png");
		} catch (Exception e)
		{
			e.printStackTrace();
			inputStream = null;
		}

		if (inputStream != null)
		{
			Bitmap bitmap = BitmapFactory.decodeStream(inputStream);

			ImageView imageProduct = (ImageView) findViewById(R.id.image_product);
			imageProduct.setImageBitmap(bitmap);
		}

		_buttonSellProduct = (Button) findViewById(R.id.button_user_sell_product);

		_buttonSellProduct.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View arg0)
			{
				_timerOutUtils.pause();

				final Box currentBox = AppMain.getInstance().getCurrentBox();

				putCommandSell(currentBox.getCommand());

				_productSell = new ProductSell();
				_productSell.setAccountNumber(AppMain.getInstance().getCurrentAccount().getId());
				_productSell.setIdBox(currentBox.getId());
				_productSell.setDelivered(false);
				_productSell.setSentServerOk(false);
				_productSell.setPrice(currentProduct.getPrice());
				_productSell.setDate(System.currentTimeMillis());
				_productSell.setMachineCode(AppMain.getInstance().getMachineInfo().getCode());
				_productSell.setCodeProduct(currentBox.getProductCode());

				// Network.sendMessage(_productSell,
				// AppMain.getInstance()._machineInfo);

				TimerTask timerTask = new TimerTask()
				{

					@Override
					public void run()
					{
						cancel();
						runOnUiThread(new Runnable()
						{

							@Override
							public void run()
							{

								Utils.debug(
										"Time out delevery!");

								_timerOutUtils.resume();
								setResult(RESULT_OK);
								showDialogCatch(R.string.message_put_command_error);

							}
						});
					}
				};
				_timerOutProductDelevery = new Timer();
				_timerOutProductDelevery.schedule(timerTask,
						Constant.TIME_OUT_WAIT_PRODUCT_DELIVERY);
			}
		});

		_timerOutUtils = new TimerOutUtils(this, R.id.text_time, false);

		_buttonSellProduct.setVisibility(View.GONE);

	}

	@Override
	public void onWindowFocusChanged(boolean hasFocus)
	{
		switch (AppMain.getInstance().getCodeResult())
		{
			case TIME_OUT_NOT_OPERATOR:
				showDialogCatch(R.string.message_time_out_user_not_operating);

				break;
			case TIME_OUT_USER:
				showDialogCatch(R.string.message_time_out_user);

				break;
			default:
				break;
		}

		AppMain.getInstance().setCodeResult(CodeResult.NONE);

		super.onWindowFocusChanged(hasFocus);
	}

	@Override
	protected Dialog onCreateDialog(int id)
	{
		if (id == R.string.message_exit_confirm_user)
		{
			return new DialogMessageConfirm(this, true, id, true, true);
		}
		else if (id == R.string.message_time_out_user)
		{
			return new DialogMessageBack(this, true, id, true);
		}
		else if (id == R.string.message_time_out_user_not_operating)
		{

			final DialogMessageConfirm dialogMessageConfirmNotOperating = new DialogMessageConfirm(
					this, false, id, true);
			OnClickListener onClickListenerYESNotOperating = new OnClickListener()
			{

				@Override
				public void onClick(View v)
				{
					dialogMessageConfirmNotOperating.cancel();
					_timerOutUtils.stopTimeOutDialog();
				}
			};
			dialogMessageConfirmNotOperating.setOnclickListenerYes(onClickListenerYESNotOperating);
			return dialogMessageConfirmNotOperating;
		}
		else if (id == R.string.message_put_command_error)
		{
			return new DialogMessageBack(this, true, id, true);
		}
		else if (id == R.string.message_put_command_ok)
		{
			return new DialogMessageBack(this, false, id, true);
		}
		else
			return super.onCreateDialog(id);
	}

	private void putCommandSell(String command)
	{
		showProgress(this);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event)
	{
		_timerOutUtils.startTimerOutUser();

		return super.onTouchEvent(event);
	}

	@Override
	protected void onResume()
	{
		_timerOutUtils.startTimerOutUser();
		_timerOutUtils.startTimerNotOperating();

		super.onResume();
	}

	private void showDialogCatch(final int id)
	{
		runOnUiThread(new Runnable()
		{

			@Override
			public void run()
			{
				try
				{
					showDialog(id);
				} catch (Exception e)
				{
					e.printStackTrace();
				}
			}
		});
	}

	@Override
	protected void onPause()
	{
		_timerOutUtils.stop();
		super.onPause();
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event)
	{
		if (KeyEvent.KEYCODE_MENU == event.getKeyCode()
				|| KeyEvent.KEYCODE_DPAD_LEFT == event.getKeyCode()
				|| KeyEvent.KEYCODE_DPAD_DOWN == event.getKeyCode()
				|| KeyEvent.KEYCODE_DPAD_RIGHT == event.getKeyCode()
				|| KeyEvent.KEYCODE_DPAD_UP == event.getKeyCode()
				|| KeyEvent.KEYCODE_DPAD_CENTER == event.getKeyCode()
				|| KeyEvent.KEYCODE_CALL == event.getKeyCode()
				|| KeyEvent.KEYCODE_CAMERA == event.getKeyCode()
				|| KeyEvent.KEYCODE_ENDCALL == event.getKeyCode()
				|| KeyEvent.KEYCODE_HOME == event.getKeyCode()
				|| KeyEvent.KEYCODE_SEARCH == event.getKeyCode()
				|| KeyEvent.KEYCODE_BACK == event.getKeyCode())
		{
			return Utils.disableAllKey(event);
		}
		else
			return super.dispatchKeyEvent(event);

	}

	@Override
	public void onAttachedToWindow()
	{
		if (AppConfig.USE_ATTACH_WINDOW_FOR_DISABLE_HOME_KEY)
		{
			this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
			super.onAttachedToWindow();
		}
	}

	@Override
	public void onConnectFail(int typeError)
	{
	}

	@Override
	public void onNetworkMessageIncomming(Transaction transaction)
	{
	}
}
